package cn.yr.clock.handler;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.yr.clock.domain.entity.User;
import cn.yr.clock.service.UserService;
import cn.yr.clock.utils.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
public class CacheUserHandler {

    @Autowired
    private TokenHandler tokenHandler;
    @Autowired
    private UserService userService;

    /**
     * 缓存器 默认90分后过期
     */
    private TimedCache<String, String> timedCache = CacheUtil.newTimedCache(1000*60*90);


    public User getUser(){
        HttpServletRequest request = ServletUtil.getRequest();
        return getUser(request);
    }

    public User getUser( HttpServletRequest request){
        String authorization = request.getHeader("Authorization");
        return getUser(authorization);
    }

    public User getUser(String token){
        if(StrUtil.isBlank(token)){
            log.info("token为空");
            return null;
        }
        Long userId = tokenHandler.getUserId(token);
        if(ObjectUtil.isNotNull(userId)){
            return getUser(userId);
        }else {
            return null;
        }

    }

    public User getUser(Long userId){
        String str = timedCache.get(String.valueOf(userId));
        if(StrUtil.isNotBlank(str)){
            return JSONUtil.toBean(str, User.class);
        }else {
            User user = userService.getById(userId);
            setUser(user);
            return user;
        }
    }

    public void setUser(User user){
        timedCache.put(String.valueOf(user.getUserId()),JSONUtil.toJsonStr(user),1000 * 60 * 60 * 24 * 14);
    }
}
